package m

import (
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

// Boss首次击杀礼包
type BossPack struct {
	BaseM
	Uid       bson.ObjectId           `bson:"_id" json:"_id"` // 用户uid
	MGiftPack map[int64]*BossPackInfo `bson:"mGiftPack" json:"mGiftPack"`
}

// 礼包信息
type BossPackInfo struct {
	MonsterID int64 `bson:"monsterID" json:"monsterID"` // 配表id，BossID
	PackId    int64 `bson:"packId" json:"packId"`       // 付费礼包id
	BeginTime int64 `bson:"beginTime" json:"beginTime"` // 起始时间
	EndTime   int64 `bson:"endTime" json:"endTime"`     // 结束时间
}

func NewBossPack() cache.EntryI {
	return &BossPack{
		MGiftPack: make(map[int64]*BossPackInfo),
	}
}

// 保存信息
func (bp *BossPack) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("BossPack", bson.M{"_id": bp.Uid}, bp)
	if err != nil {
		return err
	}
	return
}

func (bp *BossPack) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		bp.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		bp.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "BossPack_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return bp.LoadData()
}

// 加载数据
func (bp *BossPack) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("BossPack", bson.M{"_id": bp.Uid}, nil, &bp)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if bp.MGiftPack == nil {
		bp.MGiftPack = make(map[int64]*BossPackInfo)
	}
	return
}

// 更新数据
func (bp *BossPack) Update(val *BossPack) {
	Cache.Put("BossPack", val.Uid.Hex(), val)
	val.UpdateData()
}

// 获取活动礼包信息
func GetBossPack(uid string) *BossPack {
	v, _ := Cache.Get("BossPack", uid)
	return v.(*BossPack)
}
